<?php

namespace App\Console\Commands;

use App\Services\SocketService;
use Illuminate\Console\Command;

class Im extends Command
{
    /**
     * 连接
     * @var object $socket
     */
    private $socket;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'service:im';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'im';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @param SocketService $socketService
     * @return mixed
     */
    public function handle(SocketService $socketService)
    {
        // 创建WebSocket Server对象，监听0.0.0.0:9502端口
        $this->socket = new \swoole_websocket_server('0.0.0.0', 9502);

        // 设置链接配置
        $this->socket->set(config('im_option'));

        // 监听WebSocket连接打开事件
        $this->socket->on('open', [$socketService, 'onOpen']);

        // 监听WebSocket消息事件
        $this->socket->on('message', [$socketService, 'onMessage']);

        // 监听WebSocket连接关闭事件
        $this->socket->on('close', [$socketService, 'onClose']);

        // 启动连接
        $this->socket->start();
    }

}
